import { Form, type FormInstance } from "antd";
import { useEffect, useMemo } from "react";
import FormItems from "../FormItems/index.tsx";
import { useHandleFormData } from "../../hook/useHandleFormData.ts";
import type { FormItemConfigs } from "../../global.ts";

interface ModalFormProps {
  form?: FormInstance<any>;
  onFinish?: (values: any) => void;
  formItemConfigs?: FormItemConfigs[];
  initData?: any;
  children?: React.ReactNode;
}

const ModalForm = (props: ModalFormProps) => {
  const [form] = Form.useForm(props.form);
  const { onFinish, formItemConfigs = [], initData, children } = props;
  
  const { handleEditFormData, handleEditSubmitFormData } = useHandleFormData({
    editFormFieldConfig: formItemConfigs,
  });

  // 判断是否为编辑模式（通过检查配置中是否存在 id 字段）
  const isEditMode = useMemo(() => {
    return formItemConfigs.some(config => config.name === 'id');
  }, [formItemConfigs]);

  // 处理初始值
  const initialValues = useMemo(() => {
    // 编辑模式不使用 initialValues
    if (isEditMode) {
      return {};
    }

    // 收集所有配置中的 initialValue
    const values: Record<string, any> = {};
    formItemConfigs.forEach(config => {
      if ('initialValue' in config) {
        values[config.name] = config.initialValue;
        return;
      }
      // 兼容一下原来的defaultValue
      if ('defaultValue' in config) {
        values[config.name] = config.defaultValue;
      }
    });
    return values;
  }, [formItemConfigs, isEditMode]);

  // 处理编辑数据
  useEffect(() => {
    if (initData) {
      const formData = handleEditFormData(initData);
      form.setFieldsValue(formData);
    } else if (!isEditMode) {
      // 非编辑模式且没有初始数据时，重置到初始值
      form.resetFields();
    }
  }, [initData, form, handleEditFormData, isEditMode]);

  const handleOnFinish = (values: any) => {
    const processedValues = handleEditSubmitFormData(values);
    onFinish?.(processedValues);
  };

  return (
    <Form 
      form={form} 
      onFinish={handleOnFinish}
      initialValues={initialValues}
    >
      <FormItems formItemsConfigs={formItemConfigs} />
      {children}
    </Form>
  );
};

export default ModalForm;
